package com.oscar.ehome.view.messageview;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.oscar.ehome.R;
import com.oscar.ehome.base.activity.BasesActivity;
import com.oscar.ehome.bean.messageBean.MessageListBean;
import com.oscar.ehome.bean.messageBean.MessagesBean;
import com.oscar.ehome.presenter.MessageListPreaenter;
import com.oscar.ehome.utils.pullrefresh.PullToRefreshBase;
import com.oscar.ehome.utils.pullrefresh.PullToRefreshListView;
import com.oscar.ehome.utils.system.SystemConfigFactory;
import com.oscar.ehome.utils.util.CommonUtils;
import com.oscar.ehome.utils.util.ToastUtil;
import com.oscar.ehome.utils.view.progressview.ProgressFrameLayout;
import com.oscar.ehome.view.loginview.LoginActivity;
import com.oscar.ehome.view.messageview.adapter.MessageListAdapter;
import com.oscar.ehome.view.messageview.view.MessageListView;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by oscar
 * author: MengWanhe
 * date: On 2017/6/30
 * 搜索页面
 */

public class SerachMessageActivity extends BasesActivity<MessageListView, MessageListPreaenter> implements MessageListView, PullToRefreshBase.OnRefreshListener,
        AdapterView.OnItemClickListener, ProgressFrameLayout.AgainRequestListener {
    /**
     * 筛选信息
     */
//是否展示消息未读
    @BindView(R.id.message_layout)
    LinearLayout messageLayout;
    /**
     * 关闭
     */
    @BindView(R.id.message_close_re)
    RelativeLayout message_close_re;
    /**
     * 展示筛选信息
     */
    @BindView(R.id.read_message_text)
    TextView readMessageText;

    @BindView(R.id.search_shaixuan)
    LinearLayout search_ShaiXuan;
    /**
     * 输入框
     */
    @BindView(R.id.message_keyword_edtext)
    EditText messageKeywordEdtext;
    /**
     * 搜索按钮
     */
    @BindView(R.id.serach_buton)
    Button serachButon;
    /**
     * 数据展示 listview
     */
    @BindView(R.id.serachmessage_listview)
    PullToRefreshListView serachmessageListview;
    /**
     * 返回
     */
    @BindView(R.id.serachtitle_img_back)
    ImageView serachtitleImgBack;
    /**
     * 返回
     */
    @BindView(R.id.serachtitle_layout_left)
    RelativeLayout serachtitleLayoutLeft;
    /**
     * 布局
     */
    @BindView(R.id.serachmess_fragment)
    ProgressFrameLayout serachmessFragment;
    /**
     * title布局
     */
    @BindView(R.id.serach_message_title)
    RelativeLayout serach_message_title;

    //网络请求
    MessageListPreaenter presenter;
    String token = "";
    @BindView(R.id.search_weidu)
    TextView searchWeidu;
    @BindView(R.id.search_xitong)
    TextView searchXitong;
    @BindView(R.id.search_chanpin)
    TextView searchChanpin;
    @BindView(R.id.search_jili)
    TextView searchJili;
    @BindView(R.id.search_huiyi)
    TextView searchHuiyi;
    @BindView(R.id.search_tongzhi)
    TextView searchTongzhi;

    //数据源
    private List<MessageListBean> lists = new ArrayList<MessageListBean>();
    //adapter
    MessageListAdapter adapter;
    private int count = 0;//条数
    private int page = 1;//页数
    private int page_size = 20;//每页的条数
    int size = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_serachmessage);
        ButterKnife.bind(this);
        serach_message_title.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(SerachMessageActivity.this).getSystemConfig().getColor()));
        onClick();
        initView();
        initData();
        getMessage();
        //自动弹出软键盘
        messageKeywordEdtext.setFocusable(true);
        messageKeywordEdtext.setFocusableInTouchMode(true);
        messageKeywordEdtext.requestFocus();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
                           public void run() {
                               InputMethodManager inputManager =
                                       (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                               inputManager.showSoftInput(messageKeywordEdtext, 0);
                           }
                       },
                200);
    }

    @Override
    protected MessageListPreaenter createPresenter() {
        presenter = new MessageListPreaenter(this);
        return presenter;
    }

    /**
     * 判断是否有网
     */
    public boolean isNetWork() {
        boolean netWork = true;
        if (!CommonUtils.isNetConn(SerachMessageActivity.this)) {
            netWork = false;
            return netWork;
        }
        return netWork;
    }

    /**
     * 初始化
     */
    public void initView() {
        messageLayout.setVisibility(View.GONE);
        serachtitleImgBack.setImageResource(R.mipmap.fanhui);
        messageLayout.setVisibility(View.GONE);
        token = SystemConfigFactory.getInstance(SerachMessageActivity.this).getSystemConfig().getToken();
    }

    public void onClick() {
        serachmessageListview.setPullLoadEnabled(true);
        serachmessageListview.setOnRefreshListener(this);
        serachmessageListview.setOnItemClickListener(this);
        serachmessFragment.setAgainRequestListener(this);

    }

    /**
     * 加载数据
     */
    public void initData() {
        search_ShaiXuan.setVisibility(View.VISIBLE);
        adapter = new MessageListAdapter(SerachMessageActivity.this, lists);
        serachmessageListview.setAdapter(adapter);
    }

    /**
     * 设置键盘的搜索事件
     */
    public void getMessage() {
        messageKeywordEdtext.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 先隐藏键盘
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(SerachMessageActivity.this.getCurrentFocus()
                                    .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    // 搜索，进行自己要的操作...
                    checkMessage();
                    return true;
                }
                return false;
            }
        });
    }

    /**
     * 搜索数据
     */
    public void checkMessage() {
        if (isNetWork()) {
            serachmessFragment.stopRefresh();
            serachmessageListview.setVisibility(View.VISIBLE);
            if (TextUtils.isEmpty(messageKeywordEdtext.getText().toString().trim())&&CommonUtils.type .equals("")&&CommonUtils.readFlag.equals("")) {
                Toast.makeText(this, "请输入要搜索的信息", Toast.LENGTH_SHORT).show();
            } else {
                String s = String.valueOf(page);

                presenter.messagelist(token, s, "20", messageKeywordEdtext.getText().toString().trim(), CommonUtils.type , CommonUtils.readFlag);
                Log.e("请求返回", "checkMessage: "+ messageKeywordEdtext.getText().toString().trim()+CommonUtils.type +CommonUtils.readFlag);
                showLoading();
            }
        } else {
            serachmessageListview.setVisibility(View.GONE);
            serachmessFragment.setVisibility(View.VISIBLE);
            serachmessFragment.setLoadFail();
        }

    }

    @OnClick({R.id.serach_buton, R.id.serachtitle_layout_left, R.id.message_close_re,R.id.search_weidu,R.id.search_chanpin,R.id.search_huiyi,R.id.search_jili
    ,R.id.search_xitong,R.id.search_tongzhi})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.search_weidu:
                CommonUtils.type = "";
                CommonUtils.readFlags = "";
                CommonUtils.types = "";
                CommonUtils.readFlag = "";
                CommonUtils.readFlag = "0";
                CommonUtils.readFlags = "未读";
                search_ShaiXuan.setVisibility(View.GONE);
                checkMessage();
                break;
            case R.id.search_xitong:
                CommonUtils.type = "";
                CommonUtils.readFlags = "";
                CommonUtils.types = "";
                CommonUtils.readFlag = "";
                CommonUtils.type = "5";
                CommonUtils.types = "系统";
                search_ShaiXuan.setVisibility(View.GONE);
                checkMessage();
                break;
            case R.id.search_chanpin:
                CommonUtils.type = "";
                CommonUtils.readFlags = "";
                CommonUtils.types = "";
                CommonUtils.readFlag = "";
                CommonUtils.type = "3";
                CommonUtils.types = "产品";
                search_ShaiXuan.setVisibility(View.GONE);
                checkMessage();
                break;
            case R.id.search_jili:
                CommonUtils.type = "";
                CommonUtils.readFlags = "";
                CommonUtils.types = "";
                CommonUtils.readFlag = "";
                CommonUtils.type = "2";
                CommonUtils.types = "激励";
                search_ShaiXuan.setVisibility(View.GONE);
                checkMessage();
                break;
            case R.id.search_huiyi:
                CommonUtils.type = "";
                CommonUtils.readFlags = "";
                CommonUtils.types = "";
                CommonUtils.readFlag = "";
                CommonUtils.type = "4";
                CommonUtils.types = "会议";
                search_ShaiXuan.setVisibility(View.GONE);
                checkMessage();
                break;
            case R.id.search_tongzhi:
                CommonUtils.type = "";
                CommonUtils.readFlags = "";
                CommonUtils.types = "";
                CommonUtils.readFlag = "";
                CommonUtils.type = "1";
                CommonUtils.types = "通知";
                search_ShaiXuan.setVisibility(View.GONE);
                checkMessage();
                break;
            case R.id.serach_buton:
                checkMessage();
                break;
            case R.id.serachtitle_layout_left:
                CommonUtils.type = "";
                CommonUtils.readFlags = "";
                CommonUtils.types = "";
                CommonUtils.readFlag = "";

                lists.clear();

                finish();
                break;
            case R.id.message_close_re:
                CommonUtils.type = "";
                CommonUtils.readFlags = "";
                CommonUtils.types = "";
                CommonUtils.readFlag = "";
                messageKeywordEdtext.setText(null);
                serachmessFragment.stopRefresh();
                messageLayout.setVisibility(View.GONE);
                lists.clear();
                initData();
                break;
        }
    }

    @Override
    public void getMessageList(MessagesBean result) {
        dismissLoading();
        serachmessageListview.onPullDownRefreshComplete();
        serachmessageListview.onPullUpRefreshComplete();


        if (result != null) {
            lists.clear();
            lists = result.getList();
            count = result.getCount();
            if (!CommonUtils.type.equals("") || !CommonUtils.readFlags.equals("") || messageKeywordEdtext.getText().toString().trim() != null) {//筛选项
                readMessageText.setText(CommonUtils.types+CommonUtils.readFlags);
                if(readMessageText.getText()!=""){
                    if(messageKeywordEdtext.getText().toString().length()>0&&readMessageText.getText().length()>1){
                        readMessageText.append( "、"+messageKeywordEdtext.getText().toString().trim() + "(" + count + ")");
                    }else{
                        readMessageText.setText(CommonUtils.types+CommonUtils.readFlags+ messageKeywordEdtext.getText().toString().trim()+"(" + count + ")");
                    }
                }else{
                    readMessageText.setText( messageKeywordEdtext.getText().toString().trim() + "(" + count + ")");
                }


                messageLayout.setVisibility(View.VISIBLE);
            } else {
                messageLayout.setVisibility(View.GONE);
            }
            if (lists.size() == 0) {
                serachmessFragment.setNoResult();
                ToastUtil.show(SerachMessageActivity.this, "暂无消息通知，换个关键字试试吧！");
            } else {

                search_ShaiXuan.setVisibility(View.GONE);
            }
            adapter.setLists(lists);
        }
    }

    @Override
    public void deleteMessageList(String result) {

    }

    @Override
    public void erroy() {
        serachmessageListview.onPullDownRefreshComplete();
        serachmessageListview.onPullUpRefreshComplete();
        ToastUtil.show(SerachMessageActivity.this, getString(R.string.erry));
    }

    @Override
    public void erry(String result) {
        serachmessageListview.onPullDownRefreshComplete();
        serachmessageListview.onPullUpRefreshComplete();
        ToastUtil.show(SerachMessageActivity.this, result);
        if (result.contains("过期")) {
            getSharedPreferences("appbase", Context.MODE_PRIVATE).edit().clear().commit();
            SystemConfigFactory.getInstance(this).getSystemConfig().SetLogin(false);
            SystemConfigFactory.getInstance(this).getSystemConfig().setIsFirst(true);
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            finish();
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        page = 1;

        String s = String.valueOf(page);

        presenter.messagelist(token, s, "20", messageKeywordEdtext.getText().toString().trim(), CommonUtils.type , CommonUtils.readFlag);
        showLoading();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        page++;

        String s = String.valueOf(page);

        presenter.messagelist(token, s, "20", messageKeywordEdtext.getText().toString().trim(), CommonUtils.type , CommonUtils.readFlag);
        showLoading();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String ids = lists.get(position).getId();
        String type = lists.get(position).getType();
        Intent intent = new Intent(SerachMessageActivity.this, MessageDetilActivity.class);
        intent.putExtra("ids", ids);
        intent.putExtra("type", type);
        startActivity(intent);
    }

    @Override
    public void againRequest() {
        if (isNetWork()) {
            checkMessage();
        } else {
            ToastUtil.show(SerachMessageActivity.this, R.string.pull_to_refresh_network_error);
        }
    }
}
